package com.example.demo.gateway.support;

import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/4/15 20:29
 * @Description:
 */
public class ReactiveRequestContextHolder {
    private static final ThreadLocal<ServerHttpRequest> REQUEST_THREAD_LOCAL = new InheritableThreadLocal<>();

    public static final Class<ServerHttpRequest> CONTEXT_KEY = ServerHttpRequest.class;

    /**
     * Gets the {@code Mono<ServerHttpRequest>} from Reactor {@link Context}
     * @return the {@code Mono<ServerHttpRequest>}
     */
    public static Mono<ServerHttpRequest> getRequest() {
        return Mono.subscriberContext()
                .map(ctx -> ctx.get(CONTEXT_KEY));
    }

    public static void put(ServerHttpRequest request){
        REQUEST_THREAD_LOCAL.set(request);
    }

    public static ServerHttpRequest get(){
        return REQUEST_THREAD_LOCAL.get();
    }

    public static void remove(){
        REQUEST_THREAD_LOCAL.remove();
    }
}
